﻿using System;
using System.IO;
using System.Reflection;
using BluePortal.Medias.Core;
using BluePortal.Encoding.Core.ExpressionEncoder;

namespace BluePortal.Encoding.Core
{
    internal static class Utils
    {
         
        /// <summary>
        /// return full path of filename
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static string GetConfigFile(string filename)
        {
            string location = Assembly.GetExecutingAssembly().Location;
            location = Path.GetDirectoryName(location);
            return Path.Combine(location, Path.Combine("Config", filename));
        }

        //  --------------------------- CopyStream ---------------------------
        /// <summary>
        ///   Copies data from a source stream to a target stream.</summary>
        /// <param name="source">
        ///   The source stream to copy from.</param>
        /// <param name="target">
        ///   The destination stream to copy to.</param>
        public static void CopyStream(Stream source, Stream target)
        {
            Utils.CopyStream (source, target, 0x2000);
        }
        public static void CopyStream(Stream source, Stream target, int buffersize)
        {
            int bufSize = buffersize;
            byte[] buf = new byte[bufSize];
            int bytesRead = 0;
            while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
            {
                target.Write(buf, 0, bytesRead);
            }           
        }

        public static void ReadChapters(JobFile jobFile, string tmpDir, Video video)
        {
            string fileVideoName = Path.GetFileNameWithoutExtension(jobFile.Job[0].MediaFiles[0].Source);
            //Add Chapters in video with Image
            foreach( Marker m in jobFile.Job[0].MediaFiles[0].Markers)
            {
                VideoChapter videoChapter = new VideoChapter(){CID = Guid.NewGuid(), ID=video.ID, Name=m.Value, Time= TimeSpan.Parse(m.Time).Ticks};
                string filename = String.Format("{0}\\{1}_MarkerThumb {2}.jpg", tmpDir, fileVideoName, m.Time.Replace(":", "."));
                FileInfo f = new FileInfo(filename);                
                videoChapter.Image = File.ReadAllBytes(filename);
    
                video.VideoChapters.Add(videoChapter);
            }
        }
    }
}
